<template>
  <view class="container">
    <!-- 标签栏 -->
    <view class="tab-bar">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index" 
        class="tab-item" 
        :class="{ active: activeTab === tab.value }"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list" v-if="orders.length > 0">
      <view class="order-item" v-for="(order, index) in orders" :key="index" @click="goToOrderDetail(order)">
        <!-- 订单头部：店铺名称和订单状态 -->
        <view class="order-header">
          <view class="shop-name">{{ getShopName(order) }}</view>
          <view class="order-status" :class="'status-' + (order.status || '0')">
            {{ order.status_title || getOrderStatusText(order.status) }}
          </view>
        </view>
        
        <!-- 商品列表 -->
        <view class="product-list">
          <view class="product-item" v-for="(detail, dIndex) in order.detail" :key="dIndex">
            <view class="product-image-container">
              <image 
                class="product-image" 
                :src="getProductImage(detail.product.img)" 
                mode="aspectFill" 
                v-if="getProductImage(detail.product.img)"
              ></image>
              <view class="product-image-placeholder" v-else></view>
            </view>
            <view class="product-info">
              <view class="product-title-price">
                <view class="product-name">{{ detail.product.title }}</view>
                <view class="product-price">¥{{ detail.price }}</view>
              </view>
              <view class="product-spec-quantity">
                <view class="product-spec">{{ detail.product.desc || '默认规格' }}</view>
                <view class="product-quantity">x{{ detail.num }}</view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 订单底部：实付款和操作按钮 -->
        <view class="order-footer">
          <view class="order-total">实付款：¥{{ order.money }}</view>
          <view class="order-actions">
            <button class="action-button use-button" @click.stop="useOrder(order.id)">核销</button>
          </view>
        </view>
      </view>
    </view>

    
    <!-- 空数据提示 -->
    <view class="no-data" v-else>
      <view class="no-data-placeholder"></view>
      <view class="no-data-text">暂无订单数据</view>
    </view>
  </view>
</template>

<script>
import config from '../../static/config.js';
import { orderAPI } from '../../static/indexAPI.js';

export default {
  data() {
    return {
      // 标签页数据
      tabs: [
        { label: '全部', value: '' },
        { label: '待付款', value: '1' },
        { label: '待使用', value: '2' },
        { label: '已使用', value: '3' },
        { label: '已取消', value: '4' }
      ],
      activeTab: '', // 当前激活的标签，默认为"全部"
      orders: [], // 订单列表
      baseURL: config.baseURL, // API基础URL
      token: '', // 用户token
      userId: '', // 用户ID
      shopNames: {} // 存储店铺名称的缓存
    };
  },
  
  onLoad(options) {
    // 获取用户token和用户ID
    this.token = uni.getStorageSync('token') || '';
    this.userId = uni.getStorageSync('userId') || '';
    
    // 检查是否有传入的状态参数
    if (options && options.status !== undefined) {
      this.activeTab = options.status;
    }
    
    // 加载订单数据
    this.loadOrders();
  },
  
  methods: {
    // 切换标签页
    switchTab(tabValue) {
      this.activeTab = tabValue;
      this.loadOrders();
    },
    
    // 加载订单数据
    loadOrders() {
      // 显示加载提示
      uni.showLoading({
        title: '加载中...'
      });
      
      // 构造请求参数
      const params = {
        uid: this.userId
      };
      
      // 只有当status不为空时才添加到参数中
      if (this.activeTab !== '') {
        params.status = this.activeTab;
      }
      
      console.log('请求参数:', {
        url: this.baseURL + '/api/order',
        method: 'POST',
        header: {
          'token': this.token,
          'userid': this.userId
        },
        data: params
      });
      
      
      // 使用统一封装的接口
      orderAPI.getOrderList(params, this.token, this.userId).then((res) => {
        console.log('订单数据响应:', res);
        
        if (res.statusCode === 200 && res.data) {
          // 根据接口文档处理返回数据
          if (res.data.code === 1) {
            this.orders = res.data.data || [];
            console.log('订单列表:', this.orders);
            
            // 获取订单中涉及的店铺名称
            this.fetchShopNames();
          } else {
            this.orders = [];
            uni.showToast({
              title: res.data.msg || '数据加载失败',
              icon: 'none'
            });
          }
        } else {
          this.orders = [];
          uni.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
        }
      }).catch((err) => {
        console.error('订单数据加载失败:', err);
        this.orders = [];
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
      });

    },
    
    // 获取店铺名称
    getShopName(order) {
      // 从订单的第一个商品中获取店铺ID
      if (!order.detail || order.detail.length === 0) {
        return '默认店铺';
      }
      
      const shopId = order.detail[0].product.foodshop_id;
      if (!shopId) {
        return '默认店铺';
      }
      
      // 如果已经缓存了店铺名称，直接返回
      if (this.shopNames[shopId]) {
        return this.shopNames[shopId];
      }
      
      // 否则返回"加载中..."并发起请求获取店铺信息
      this.fetchShopDetail(shopId);
      return '加载中...';
    },
    
    // 获取店铺详情
    fetchShopDetail(shopId) {
      // 避免重复请求
      if (this.shopNames[shopId] || this.shopNames[shopId] === '加载中...') {
        return;
      }
      
      // 设置为加载中状态
      this.$set(this.shopNames, shopId, '加载中...');
      
      uni.request({
        url: this.baseURL + '/api/food/shop_detail',
        method: 'POST',
        data: {
          id: shopId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 1) {
            // 缓存店铺名称
            this.$set(this.shopNames, shopId, res.data.data.title || '未知店铺');
          } else {
            this.$set(this.shopNames, shopId, '未知店铺');
          }
        },
        fail: (err) => {
          console.error('获取店铺详情失败:', err);
          this.$set(this.shopNames, shopId, '未知店铺');
        }
      });
    },
    
    // 获取订单中所有店铺的名称
    fetchShopNames() {
      // 提取所有唯一的店铺ID
      const shopIds = [];
      
      this.orders.forEach(order => {
        if (order.detail && order.detail.length > 0) {
          const shopId = order.detail[0].product.foodshop_id;
          if (shopId && !shopIds.includes(shopId)) {
            shopIds.push(shopId);
          }
        }
      });
      
      // 为每个店铺ID获取店铺详情
      shopIds.forEach(shopId => {
        this.fetchShopDetail(shopId);
      });
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        '1': '待付款',
        '2': '待使用',
        '3': '已使用',
        '4': '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取商品图片完整URL
    getProductImage(imageUrl) {
      // 如果没有图片，返回空字符串，使用默认占位符
      if (!imageUrl) return '';
      
      // 如果已经是完整URL，直接返回
      if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        return imageUrl;
      }
      
      // 拼接基础URL
      return this.baseURL + imageUrl;
    },
    
    // 跳转到订单详情
    goToOrderDetail(order) {
      // 将订单数据存储到全局存储中，以便在详情页面使用
      uni.setStorageSync('currentOrder', order);
      uni.navigateTo({
        url: '/pages/orderdetail/orderdetail?id=' + order.id
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 0; /* 移除为固定导航栏留出的空间 */
}

/* 标签栏样式 */
.tab-bar {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 10px 0;
  position: sticky;
  top: 0;
  z-index: 998;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #666;
  padding: 8px 0;
}

.tab-item.active {
  font-weight: bold;
  position: relative;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 3px;
  background-color: #FFC400;
  border-radius: 3px;
}

/* 订单列表样式 */
.order-list {
  padding: 10px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.shop-name {
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

.order-status {
  font-size: 14px;
}


.order-status.status-2 {
  color: #1aad19;
}

.order-status.status-3 {
  color: #999;
}

.order-status.status-4 {
  color: #ccc;
}

/* 商品列表样式 */
.product-list {
  margin-bottom: 10px;
}

.product-item {
  display: flex;
  margin-bottom: 15px;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-image-container {
width: 26%;
    margin-right: 10px;
}

.product-image {
  width: 100%;
  height: 75px;
  border-radius: 4px;
}

.product-image-placeholder {
  width: 100%;
  height: 60px;
  border-radius: 4px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  // justify-content: space-between; 
  width: 60%;
}

.product-title-price {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.product-name {
  font-size: 15px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 5px;
}

.product-price {
  font-size: 14px;
  font-weight: bold;
  flex-shrink: 0;
}

.product-spec-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
  width: 100%;
}

.product-spec {
  font-size: 13px;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 5px;
  min-width: 0; /* 允许 flex item 收缩到内容宽度以下 */
}

.product-quantity {
  font-size: 13px;
  color: #666;
}

.order-footer {
  border-top: 1px solid #eee;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-total {
  font-size: 14px;
  color: #333;
}

.order-actions {
  display: flex;
}

.action-button {
  font-size: 12px;
  padding: 0px 10px;
  margin-left: 10px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background-color: #fff;
}

.cancel-button {
  color: #999;
  border-color: #999;
}

.use-button {
  color: #fff;
  background-color: #FF8D1A;
}

/* 无数据样式 */
.no-data {
  text-align: center;
  padding: 50px 0;
}

.no-data-placeholder {
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
  background-color: #f5f5f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
  margin-bottom: 20px;
}

.no-data-text {
  font-size: 16px;
  color: #999;
}
</style>